package com.atguigu.gulimall.order.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.exception.NoStockException;
import com.atguigu.common.to.mq.OrderTo;
import com.atguigu.common.utils.R;
import com.atguigu.common.vo.MemberRespVo;
import com.atguigu.gulimall.order.config.ThreadPoolConfigProperties;
import com.atguigu.gulimall.order.constant.OrderConstant;
import com.atguigu.gulimall.order.dao.OrderItemDao;
import com.atguigu.gulimall.order.entity.OrderItemEntity;
import com.atguigu.gulimall.order.enume.OrderStatusEnum;
import com.atguigu.gulimall.order.feign.CartFeignService;
import com.atguigu.gulimall.order.feign.MemberFeignService;
import com.atguigu.gulimall.order.feign.ProductFeignService;
import com.atguigu.gulimall.order.feign.WmsFeignService;
import com.atguigu.gulimall.order.interceptor.LoginUserInterceptor;
import com.atguigu.gulimall.order.service.OrderItemService;
import com.atguigu.gulimall.order.to.OrderCreateTo;
import com.atguigu.gulimall.order.vo.*;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.order.dao.OrderDao;
import com.atguigu.gulimall.order.entity.OrderEntity;
import com.atguigu.gulimall.order.service.OrderService;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

@Slf4j
@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {

    //线程传递订单提交封装
    private ThreadLocal<OrderSubmitVo> confirmVoThreadLocal = new ThreadLocal<>();

    @Autowired
    RabbitTemplate rabbitTemplate;

    //循环依赖!!!!!!!!!!!!!!!
//    @Autowired
//    OrderService orderService;
    //订单项Service
    @Autowired
    OrderItemService orderItemService;
    //订单mapper
    @Autowired
    OrderDao orderDao;
    //订单项mapper
    @Autowired
    OrderItemDao orderItemDao;

    @Autowired
    MemberFeignService memberFeignService;

    //商品服务远程客户端
    @Autowired
    ProductFeignService productFeignService;

    @Autowired
    CartFeignService cartFeignService;

    @Autowired
    ThreadPoolExecutor executor;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    WmsFeignService wmsFeignService;
    @Autowired
    private ThreadPoolConfigProperties threadPoolConfigProperties;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public OrderConfirmVo confirmOrder() throws ExecutionException, InterruptedException {
        OrderConfirmVo confirmVo = new OrderConfirmVo();
        MemberRespVo memberRespVo = LoginUserInterceptor.loginUser.get();
        System.out.println("主线程..." + Thread.currentThread().getId());

        //获取之前的请求
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();

        CompletableFuture<Void> getAddressFuture = CompletableFuture.runAsync(() -> {
            //1.远程查询所有的收货地址列表
            System.out.println("member线程..." + Thread.currentThread().getId());
            //每一个线程都来共享之前的请求数据
            RequestContextHolder.setRequestAttributes(requestAttributes);
            List<MemberAddressVo> address = memberFeignService.getAddress(memberRespVo.getId());
            confirmVo.setMemberAddressVos(address);
        }, executor);


        CompletableFuture<Void> cartFuture = CompletableFuture.runAsync(() -> {
            //2.远程查询购物车所选中的购物项
            System.out.println("cart线程..." + Thread.currentThread().getId());
            //每一个线程都来共享之前的请求数据
            RequestContextHolder.setRequestAttributes(requestAttributes);
            List<OrderItemVo> items = cartFeignService.getCurrentUserCartItems();
            confirmVo.setItems(items);
            //feign在远程调用之前要构造1请求,调用很多的拦截器
            //RequestInterceptor interceptor : requestInterceptors
        }, executor).thenRunAsync(() -> {
            List<OrderItemVo> items = confirmVo.getItems();
            List<Long> collect = items.stream().map(item -> item.getSkuId()).collect(Collectors.toList());

            //TODO 一定要启动库存服务,否则库存查不出
            R hasStock = wmsFeignService.getSkuHasStock(collect);
            List<SkuStockVo> data = hasStock.getData(new TypeReference<List<SkuStockVo>>() {
            });
            if (data != null) {
                Map<Long, Boolean> map = data.stream().collect(Collectors.toMap(SkuStockVo::getSkuId, SkuStockVo::getHasStock));
                confirmVo.setStocks(map);
            }
        }, executor);

        //3.查询用户积分
        Integer integration = memberRespVo.getIntegration();
        confirmVo.setIntegration(integration);

        //4.其他数据自动计算

        //TODO 5.防重令牌
        String token = UUID.randomUUID().toString().replace("-", "");
        redisTemplate.opsForValue().set(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberRespVo.getId(), token, 30, TimeUnit.MINUTES);
        confirmVo.setOrderToken(token);

        CompletableFuture.allOf(getAddressFuture, cartFuture).get();

        return confirmVo;
    }


    //同一个对象内事务方法互调默认失效.原因 绕过了代理对象

    //事务使用代理对象来控制的
    @Transactional(timeout = 30)//a事务的所有设置就传播到了和他公用一个事务的方法
    public void a(){
        //b,c做任何设置都没有.都是a公用一个事务
//        this.b();没用
//        this.c();没用
        OrderServiceImpl orderService  = (OrderServiceImpl) AopContext.currentProxy();
        orderService.b();
        orderService.c();

//        bService.b();//a事务
//        cService.c();//新事务(不回滚)
        int i = 10/0;
    }
    //timeout=30在a方法中
    @Transactional(propagation = Propagation.REQUIRED,timeout = 2)
    public void b(){
        //7s
    }
    //timeout=20在a方法内
    @Transactional(propagation = Propagation.REQUIRES_NEW,timeout = 20)
    public void c(){

    }
    /**
     * 下单
     *
     * @param vo
     * @return
     */
    //本地事务,在分布式系统,只能控制住自己的回滚.控制不了其他服务的回滚
    //分布式事务,最大原因.网络问题+分布式机器
    //(isolation = Isolation.REPEATABLE_READ)
    //REQUIRED,REQUIRES_NEW
//    @GlobalTransactional 高并发
    @Transactional
    @Override
    public SubmitOrderResponseVo submitOrder(OrderSubmitVo vo) {
        //线程传递数据
        confirmVoThreadLocal.set(vo);
        //返回的封装
        SubmitOrderResponseVo response = new SubmitOrderResponseVo();
        //拿到当前登录的用户
        MemberRespVo memberRespVo = LoginUserInterceptor.loginUser.get();
        //设置当前为正常
        response.setCode(0);
        //1.验证令牌[令牌的对比和删除必须保证原子性]
        //Lua脚本 如果redis获取的令牌和传入的令牌相同,删除令牌,返回1,否则返回0
        //0令牌失败 -1删除成功
        String script = "if redis.call('get',KEYS[1]) == ARGV[1] then return redis.call('del',KEYS[1]) else return 0 end";
        //获取提交的令牌
        String orderToken = vo.getOrderToken();
        //原子验证令牌和删除令牌
        //执行脚本
        Long result = redisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class), Arrays.asList(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberRespVo.getId()), orderToken);
        //如果令牌验证失败
        if (result == 0L) {
            //返回封装
            //状态设置为错误
            response.setCode(1);
            return response;

        } else {//否则,令牌验证成功
            //下单:去创建订单,验令牌,验价格,锁库存
            //1.创建订单,订单项等信息
            //创建订单
            OrderCreateTo order = createOrder();
            //2,验价
            //获取订单总额
            BigDecimal payAmount = order.getOrder().getPayAmount();
            //获取页面价格
            BigDecimal payPrice = vo.getPayPrice();
            //对比价格,小于0.01,成功
            if (Math.abs(payAmount.subtract(payPrice).doubleValue()) < 0.01) {
                //金额对比
                //...
                //TODO 3.保存订单
                saveOrder(order);
                //4.库存锁定,只要有异常,回滚订单数据
                //订单号,所有订单项(skuId,skuName,num)
                //锁定库存封装
                WareSkuLockVo lockVo = new WareSkuLockVo();
                //封装订单号
                lockVo.setOrderSn(order.getOrder().getOrderSn());
                //转换保留有用数据
                List<OrderItemVo> locks = order.getOrderItems().stream().map(item -> {
                    //生成vo
                    OrderItemVo itemVo = new OrderItemVo();
                    //封装skuId
                    log.info("订单项skuId:{}", item.getSkuId());
                    itemVo.setSkuId(item.getSkuId());
                    //封装数量
                    itemVo.setCount(item.getSkuQuantity());
                    //封装名字
                    itemVo.setTitle(item.getSkuName());
                    //返回
                    return itemVo;
                }).collect(Collectors.toList());//收集为List
                //封装锁定数据
                lockVo.setLocks(locks);
                //TODO 4.远程锁库存
                //为了保证高并发.库存服务自己回滚.可以发消息给库存服务;
                //库存服务本身也可以使用自动解锁模式  消息
                //库存成功了,但是网络原因超时了,订单回滚,库存不滚.
                //锁定库存
                R r = wmsFeignService.orderLockStock(lockVo);
                //如果成功
                if (r.getCode() == 0) {
                    //锁成功了
                    //封装订单
                    response.setOrder(order.getOrder());
                    //TODO 5.远程扣减积分
                    //模拟远程服务失败,远程事务是否回滚
//                    int i = 10/0;
                    //返回
                    //TODO 订单创建成功发送消息给MQ
                    rabbitTemplate.convertAndSend("order-event-exchange","order.create.order",order.getOrder());
                    return response;
                } else {
                    //锁失败了
                    //回滚
                    String msg = (String) r.get("msg");
                    throw new NoStockException(msg);
                    //设置失败
//                        response.setCode(3);//失败
                    //返回
//                        return response;

                }


            } else {//否则,对比失败
                //设置状态
                response.setCode(2);//2 失败
                //返回封装
                return response;
            }
        }
//        //获取redis中的令牌
//        String redisToken = redisTemplate.opsForValue().get(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberRespVo.getId());
//        //如果提交的数据的令牌不为空并且和当前登录的令牌相同,通过.
//        if(orderToken!=null && orderToken.equals(redisToken)){
//            //删除登录的令牌
//            redisTemplate.delete(OrderConstant.USER_ORDER_TOKEN_PREFIX+memberRespVo.getId());
//        }else{//否则.不通过
//            return null;
//        }
        //返回封装数据


    }

    /**
     * 获得订单
     * @param orderSn
     * @return
     */
    @Override
    public OrderEntity getOrderByOrderSn(String orderSn) {
        //查询订单
        OrderEntity order_sn = this.getOne(new QueryWrapper<OrderEntity>().eq("order_sn", orderSn));
        //返回
        return order_sn;
    }

    /**
     * 关闭订单
     */
    @Override
    public void closeOrder(OrderEntity entity) {
        //查询当前这个订单的最新状态
        OrderEntity orderEntity = this.getById(entity.getId());
        //如果是待付款状态
        if(orderEntity.getStatus()==OrderStatusEnum.CREATE_NEW.getCode()){
            //关单
            //创建新的订单实体
            OrderEntity update = new OrderEntity();
            //设置id
            update.setId(orderEntity.getId());
            //设置状态为取消
            update.setStatus(OrderStatusEnum.CANCLED.getCode());
            //更新
            this.updateById(update);
            //创建TO
            OrderTo orderTo = new OrderTo();
            //数据对拷
            BeanUtils.copyProperties(orderEntity,orderTo);
            //尝试
            try{
                //发给MQ一个
                //TODO 保证消息一定会发送出去,每一个消息都可以做好日志记录(给数据库保存每一个消息的详细信息)
                //TODO 定期扫描数据库将失败的消息再发送一遍
                rabbitTemplate.convertAndSend("order-event-exchange","order.release.other",orderTo);
            } catch (AmqpException e) {
                //TODO 将没发送成功的消息进行重试发送
                throw new RuntimeException(e);
            }

        }
    }

    /**
     * 保存订单数据
     */
    private void saveOrder(OrderCreateTo order) {
        //获取订单
        OrderEntity orderEntity = order.getOrder();
        //设置修改时间为当前时间
        orderEntity.setModifyTime(new Date());
        //保存数据
        this.save(orderEntity);
        //获取订单项列表
        List<OrderItemEntity> orderItems = order.getOrderItems();
        //批量保存订单项
        orderItemService.saveBatch(orderItems);
    }

    //创建订单
    private OrderCreateTo createOrder() {
        //生成创建订单封装
        OrderCreateTo createTo = new OrderCreateTo();
        //生成订单号(Id唯一)
        String orderSn = IdWorker.getTimeId();
        //订单封装,根据订单号
        OrderEntity orderEntity = buildOrder(orderSn);
        //获取订单项列表,根据订单号
        List<OrderItemEntity> itemEntities = buildIrderItems(orderSn);
        //计算价格,积分
        computePrice(orderEntity, itemEntities);
        //封装订单
        createTo.setOrder(orderEntity);
        //封装订单项
        createTo.setOrderItems(itemEntities);

        //返回封装数据
        return createTo;
    }

    /**
     * 计算价格,积分
     *
     * @param orderEntity  订单
     * @param itemEntities 订单项列表
     */
    private void computePrice(OrderEntity orderEntity, List<OrderItemEntity> itemEntities) {
        //总价初始化
        BigDecimal total = new BigDecimal("0.0");
        //优惠总价
        BigDecimal coupon = new BigDecimal("0.0");
        //积分总价
        BigDecimal integration = new BigDecimal("0.0");
        //打折总价
        BigDecimal promotion = new BigDecimal("0.0");
        //总积分
        BigDecimal gift = new BigDecimal("0.0");
        //总成长值
        BigDecimal growth = new BigDecimal("0.0");
        //订单的总额,叠加每一个订单项的总额信息
        //循环订单列表
        for (OrderItemEntity entity : itemEntities) {
            //叠加优惠
            coupon = coupon.add(entity.getCouponAmount());
            //叠加积分
            integration = integration.add(entity.getIntegrationAmount());
            //叠加打折
            promotion = promotion.add(entity.getPromotionAmount());
            //叠加总价格
            total = total.add(entity.getRealAmount());
            //叠加积分
            gift = gift.add(new BigDecimal(entity.getGiftIntegration().toString()));
            //获取成长值
//            growth = entity.getGiftGrowth();
            //叠加成长值
            growth = growth.add(new BigDecimal(entity.getGiftGrowth().toString()));
        }
        //订单价格相关
        //封装订单总额
        orderEntity.setTotalAmount(total);
        //应付总额
        //封装订单的应付价格(加运费)
        orderEntity.setPayAmount(total.add(orderEntity.getFreightAmount()));
        //封装优惠
        orderEntity.setPromotionAmount(promotion);
        //封装积分
        orderEntity.setIntegrationAmount(integration);
        //封装打折
        orderEntity.setCouponAmount(coupon);
        //设置积分等信息
        //封装积分
        orderEntity.setIntegration(gift.intValue());
        //封装成长值
        orderEntity.setGrowth(growth.intValue());
        //设置删除状态
        orderEntity.setDeleteStatus(0);// 0未删除

    }

    /**
     * 订单封装
     *
     * @param orderSn
     * @return
     */
    private OrderEntity buildOrder(String orderSn) {
        //从拦截器获取登录用户
        MemberRespVo respVo = LoginUserInterceptor.loginUser.get();
        //生成订单封装
        OrderEntity entity = new OrderEntity();
        //封装订单的订单Id
        entity.setOrderSn(orderSn);
        //从登录用户得到会员id,封装
        entity.setMemberId(respVo.getId());
        //从线程获取提交的数据
        OrderSubmitVo submitVo = confirmVoThreadLocal.get();
        //获取邮递信息
        R fare = wmsFeignService.getFare(submitVo.getAddrId());
        //转换数据
        FareVo fareResp = fare.getData(new TypeReference<FareVo>() {
        });

        //封装订单,根据邮寄信息
        //封装运费金额给订单
        entity.setFreightAmount(fareResp.getFare());
        //封装订单的收货城市
        entity.setReceiverCity(fareResp.getAddress().getCity());
        //封装收货人的详情
        entity.setReceiverDetailAddress(fareResp.getAddress().getDetailAddress());
        //封装收货人名字
        entity.setReceiverName(fareResp.getAddress().getName());
        //封装手机号
        entity.setReceiverPhone(fareResp.getAddress().getPhone());
        //封装邮编
        entity.setReceiverPostCode(fareResp.getAddress().getPostCode());
        //封装省区
        entity.setReceiverProvince(fareResp.getAddress().getProvince());
        //封装区域
        entity.setReceiverRegion(fareResp.getAddress().getRegion());
        //设置订单相关状态信息
        //封装订单状态
        entity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        //设置自动确认时间
        entity.setAutoConfirmDay(7);
        //返回封装数据
        return entity;
    }

    /**
     * 构建数据库订单列表
     *
     * @return
     */
    private List<OrderItemEntity> buildIrderItems(String orderSn) {
        //最后确定每个购物项的价格
        //获取订单列表,根据当前用户
        List<OrderItemVo> currentUserCartItems = cartFeignService.getCurrentUserCartItems();
        //如果存在订单列表
        if (currentUserCartItems != null && currentUserCartItems.size() > 0) {
            //处理订单列表为数据库类型
            List<OrderItemEntity> itemEntities = currentUserCartItems.stream().map(careItem -> {
                //转换订单数据项
                OrderItemEntity itemEntity = buildIrderItem(careItem);
                //封装订单项的订单Id
                itemEntity.setOrderSn(orderSn);
                //返回订单数据项
                return itemEntity;
            }).collect(Collectors.toList());//收集为列表
            //返回订单列表(数据库)
            return itemEntities;
        }
        //否则,返回空
        return null;
    }

    /**
     * 构建数据库订单项
     *
     * @param careItem
     * @return
     */

    private OrderItemEntity buildIrderItem(OrderItemVo careItem) {
        //生成订单项
        OrderItemEntity itemEntity = new OrderItemEntity();
        //1.订单信息:订单号 v
        //2.商品的SPU信息
        //获取skuId
        Long skuId = careItem.getSkuId();
        //SpU信息
        R r = productFeignService.getSpuInfoBySkuId(skuId);
        //转spuVO
        SpuInfoVo data = r.getData(new TypeReference<SpuInfoVo>() {
        });
        //封装spuId
        itemEntity.setSpuId(data.getId());
        //封装品牌
        itemEntity.setSpuBrand(data.getBrandId().toString());
        //封装spu名字
        itemEntity.setSpuName(data.getSpuName());
        //封装分类Id
        itemEntity.setCategoryId(data.getCatalogId());

        //3.商品的sku信息 v
        //封装SkuId
        itemEntity.setSkuId(careItem.getSkuId());
        //封装标题
        itemEntity.setSkuName(careItem.getTitle());
        //封装图片
        itemEntity.setSkuPic(careItem.getImage());
        //封装价格
        itemEntity.setSkuPrice(careItem.getPrice());
        //转collection到String
        String SkuAttr = StringUtils.collectionToDelimitedString(careItem.getSkuAttr(), ";");
        //封装属性
        itemEntity.setSkuAttrsVals(SkuAttr);
        //封装数量
        itemEntity.setSkuQuantity(careItem.getCount());
        //4.优惠信息[不做]
        //5.积分信息
        //封装成长积分
        itemEntity.setGiftGrowth(careItem.getPrice().multiply(new BigDecimal(careItem.getCount().toString())).intValue());
        //封装购物积分
        itemEntity.setGiftIntegration(careItem.getPrice().multiply(new BigDecimal(careItem.getCount().toString())).intValue());
        //6.订单项的价格信息
        //封装促销价格
        itemEntity.setPromotionAmount(new BigDecimal("0"));
        //封装优惠券价格
        itemEntity.setCouponAmount(new BigDecimal("0"));
        //封装积分价格
        itemEntity.setIntegrationAmount(new BigDecimal("0"));
        //原始价格
        BigDecimal orign = itemEntity.getSkuPrice().multiply(new BigDecimal(itemEntity.getSkuQuantity()));
        //当前订单项的实际金额
        BigDecimal subtract = orign.subtract(itemEntity.getCouponAmount())
                .subtract(itemEntity.getPromotionAmount())
                .subtract(itemEntity.getIntegrationAmount());
        //封装实际价格
        itemEntity.setRealAmount(subtract);
        return itemEntity;
    }


}